<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2019/3/25
 * Time: 17:24
 */
namespace Modules\Service\Logic;
use App\Models\Address;
use App\Models\Region;
use App\Models\User;
use function foo\func;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class AddressLogic extends BaseLogic{
    /**
     * 全国行政区
     * @return false|string
     */
    public function getCityList()
    {
        $key = 'jiayouhui';
        if (!Redis::connection('default')->exists($key)) {
            $city = $this->getChinaCity();
            Redis::connection('default')->setex($key, 315360000 , json_encode($city));
        }
        $city = Redis::connection('default')->get($key);
        return json_decode($city,true);
    }

    /**
     * 获取全国城市
     * @return mixed
     */
    public function getChinaCity(){
        $province = (new Region())->where("level",1)->select("code","name")->get();
        $data = [];
        if (count($province)>0){
            array_map(function ($item)use(&$data){
                $city = (new Region())->where("parent_code",$item['code'])->select("code","name")->get();
                $citys = [];
                if (count($city)>0){
                    array_map(function ($value)use(&$citys){
                        $value['child'] = (new Region())->where("parent_code",$value['code'])->select("code","name")->get();
                        array_push($citys,$value);
                    },json_decode($city,true));
                }
                $item['child'] = $citys;
                array_push($data,$item);
            },json_decode($province,true));
        }
        return $data;
    }

    /**
     * 添加收货地址
     * @param $userId
     * @param $username
     * @param $phone
     * @param $province
     * @param $district
     * @param $city
     * @param $address
     * @param $postalCode
     * @param int $selected
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public static function addressAdd($userId,$username,$phone,$province,$city,$district,$address,$postalCode,$selected=0){
        try{
            $user = (new User())->find($userId);
            if (!$user){
                return fail(1014,"用户不存在");
            }
            $count = Address::where("user_id",$userId)->count();
            if ($count===0 && $selected===0){
                $selected = 1;
            }
            if ($selected==1){
                Address::where("user_id",$userId)->where("selected",1)->update(["selected"=>0]);
            }
            $as = new Address();
            $as->user_id = $userId;
            $as->username = $username;
            $as->phone = $phone;
            $as->province = $province;
            $as->city = $city;
            $as->district = $district;
            $as->address = $address;
            $as->postal_code = $postalCode;
            $as->selected = $selected;
            $as->save();

            return success(["id"=>$as->id]);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    /**
     * 编辑收货地址
     * @param $id
     * @param null $username
     * @param null $phone
     * @param null $province
     * @param null $city
     * @param null $district
     * @param null $address
     * @param null $postalCode
     * @param null $selected
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public static function addressEdit($id,$username=null,$phone=null,$province=null,$city=null,$district=null,$address=null,$postalCode=null,$selected=null){
        try{
            //查询收货地址
            $as = Address::find($id);
            if (!$as)return fail(1018,"收货地址不存在");
            //查询该用户是否只有一个地址
            $count = Address::where("user_id",$as->user_id)->count();
            if ($count!=1) {
                if ($selected == 1 && $as->selected == 0) {
                    //修改默认收货地址
                    Address::where("user_id", $as->user_id)->where("id", "!=", $id)->update(["selected" => 0]);
                }
            }

            if (!empty($username)) {
                $as->username = $username;
            }
            if (!empty($phone)) {
                $as->phone = $phone;
            }
            if (!empty($province)){
                $as->province = $province;
            }
            if (!empty($city)) {
                $as->city = $city;
            }
            if (!empty($district)){
                $as->district = $district;
            }
            if (!empty($address)) {
                $as->address = $address;
            }
            if (!empty($postalCode)) {
                $as->postal_code = $postalCode;
            }
            if (!empty($area_code)) {
                $as->area_code = $area_code;
            }
            $as->selected = $selected;
            $as->save();
            return success();
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,'系统错误');
        }
    }

    /**
     * 删除收货地址
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public static function addressDel($id){
        try{
            //查询收货地址
            $object = Address::find($id);
            if (!$object)return fail(1018,"收货地址不存在");
            $delData = Address::where("id",$id)->delete();
            if ($delData)return success();
            else return fail(1019,"收货地址删除失败");
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }


    /**
     * 查询默认收货地址
     * @param $userId
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public static function addressSelectFind($userId){
        try{
            //查询默认收货地址
            $selected = Address::where("user_id",$userId)->where("selected",1)->select('id','username','phone','province','city','district','address','postal_code','selected')->first();
            if (!$selected){
                $selected = Address::where("user_id",$userId)->orderBy("id","desc")->select('id','username','phone','province','city','district','address','postal_code','selected')->first();
                if (!$selected){
                    return fail(1018,"暂未添加收货地址");
                }
            }
            return success($selected);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    /**
     * 收货地址列表
     * @param $userId
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public static function addressUserAll($userId){
        try{
            $data = Address::where("user_id",$userId)->orderBy('id','desc')->select('id','username','phone','province','city','district','address','postal_code','selected')->get();
            return success($data);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }
}